﻿using Devices;
using Devices.Pukang;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Windows;
using System.Windows.Controls;

namespace DevicesWPF.UCDevices
{
    /// <summary>
    /// UCFF_6450.xaml 的交互逻辑
    /// </summary>
    public partial class UCPukang_PE6800_Vet : UserControl, IUCConfig
    {
        KukangVetBaseConfig config;
        PE6800_Vet info;
        public UCPukang_PE6800_Vet()
        {
            InitializeComponent();
        }
        public UCPukang_PE6800_Vet(PE6800_Vet _info)
        {
            InitializeComponent();
            this.info = _info;
        }

        /// <summary>
        /// 读取配置
        /// </summary>
        /// <param name="hasErrors"></param>
        /// <returns></returns>
        public Config GetConfig(out int hasErrors)
        {
            hasErrors = 0;
            Config cf = info.Config;
            config = (KukangVetBaseConfig)cf;
            config.CurrentConnectType = ConnectType.TCP;
            config.IP = labelIP.Text;
            config.Port = int.Parse(textPort.Text);
            return cf;
        }

        private void NewUCNX500IVCConfig_Load(object sender, RoutedEventArgs e)
        {
            if (this.info != null)
            {
                config = (KukangVetBaseConfig)info.Config;
                radioButtonTCP.IsChecked = true;
                if (string.IsNullOrEmpty(config.IP))
                {
                    IPAddress ip = GetLocalIPAddress();
                    if (ip == null)
                    {
                        MessageBox.Show("请打开本机IPV4网络连接");
                        return;
                    }
                    config.IP = ip.ToString();
                }
                textPort.Text = "" + config.Port;
                labelIP.Text = config.IP;
            }
        }

        private IPAddress GetLocalIPAddress()
        {
            IPAddress[] ips = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
            ips = ips?.Where(o => o.AddressFamily == AddressFamily.InterNetwork)?.ToArray();
            return ips == null || ips.Length == 0 ? null : ips[0];
        }
    }
}
